const utils = require('utility');
var cdcAppApi = require('./app-api');
const co = require("co")
var {
  OrderListNedb
} = require("./../services/businessNedb");
var {
  cdcLogger, uncaughtExceptionLogger, taskLogger
} = require("./../services/log");
var config = require('./../../config');
const appUrl = config.app.app;
const cdcUrl = config.app.cdcUrl;
const notifyHost = config.app.notifyHost;
const {
  Response
} = require("./../services/Response");
const {
  payLogger
} = require("./../services/log");
const {
  fetch
} = require("tiny-fetch");
const taskManage = require("./../services/taskManage")
var {
  getInfo, formatTime
} = require("./../services/utils")
const {
  PayingTask, PaidTask, NoticedTask, RefundTask
} = require("./../services/wechatFastTasks")
const {
  cancelOrderToFbs, refundOrderToFbs, refundOrderToApp, notifyOrderToCns,
  getOrderFromFbs, refundOrderFromApp, getOrderFromApp, completeOrderToFbs
} = require("./../services/requestService")


module.exports = function(router) {
  router.post('/pay/notify/wechat', function*(req, res, next) {
    let payObj = {};
    let result;
    let message = req.body.scanPayQueryResData;
    payObj.payments = [{
      id: message.transaction_id,
      channel: "wechat-pay",
      channelId: "wechat-pay",
      amount: (+message.total_fee) / 100,
      received: (+message.total_fee) / 100,
      payMode: "pay",
      createTime: new Date().getTime(),
      extended: {
        trade_type: message.trade_type
      }
    }];
    payObj.statusType = "weixinorder"
    payObj.orderNo = message.out_trade_no;
    payObj.amountDue = (+message
      .total_fee) / 100;

    result = yield fetch(
      cdcUrl + '/order/completePay', {
        method: 'PUT',
        body: payObj,
        headers: {
          token: "5429ca08df50392c974c5e71b8db12ab"
        }
      })


    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    const orderId = result.data.data.orderNo;
    taskManage.removeTaskByOrderId(orderId);
    let o = {
      storeId: result.data.data.storeId,
      msg: {
        type: "orderChecked",
        content: result.data.data
      }
    }
    let noticedTask = new NoticedTask(payObj.orderNo, o);
    noticedTask.onChecked = function(args) {
      return co(function*() {
        if (args) {
          taskManage.removeTask(noticedTask);
        } else {
          let result = yield notifyOrderToCns(o);
        }
      }).catch(function(e) {
        taskLogger.error({
          task: noticedTask,
          error: e.stack || e.message || e.statusMessage || e
        })
      })
    }
    taskManage.add(noticedTask);
    return res.json(Response(200));

  })


  router.post('/order/:orderId/refund', function*(req, res, next) {
    // return res.json(Response(200, "退款成功", req.body)) //debug

    let result = yield getOrderFromFbs(req.params.orderId);
    if (result.code != 200) {
      result.custom = true;
      throw result;
    }
    if (result.data && result.data.processStatus &&
      result.data.processStatus
      .status == "received") {
      return res.json(Response(201, "消息已通知成功", result.data))
    }
    if (result.data && result.data.orderType == "refund") {
      return res.json(Response(202, "订单已退款", result.data))
    }

    result = yield refundOrderFromApp(result.data);
    const resData = result.resData;
    if (resData && resData.transaction_id) {
      //退款成功
      res.json(Response(200, "退单成功", resData));
      const params = {
        orderNo: req.params.orderId,
        refundAmount: 0 - (1 * resData.refund_fee) / 100,
        serialNo: resData.transaction_id
      }
      params.payments = [{
        id: resData.refund_id,
        channel: "wechat-pay",
        channelId: "wechat-pay",
        amount: 0 - (1 * resData.refund_fee) / 100,
        received: 0 - (1 * resData.refund_fee) / 100,
        payMode: "pay",
        createTime: new Date().getTime()
      }];
      let refundTask = new RefundTask(params.orderNo, params);
      refundTask.onChecked = function(args) {
        return co(function*() {
          if (args) {
            taskManage.removeTask(refundTask);
          } else {
            let result = yield refundOrderToFbs(params);
            taskManage.removeTask(refundTask);
          }
        }).catch(function(e) {
          taskLogger.error({
            task: refundTask,
            error: e.stack || e.message || e.statusMessage || e
          })
        })
      }
      taskManage.add(refundTask);
    } else {
      //退款失败
      result.custom = true;
      throw result;
    }


  })

  router.post('/order/pay/wechat', function*(req, res, next) {
    // return res.json(Response(200)); //debug
    const now = new Date().getTime();
    var o = {
      "storeId": req.body.storeId,
      "payAmount": req.body.subtotal * 100, //1 debug
      "orderId": req.body.id,
      "wechatOrderId": req.body.id,
      "tradeType": "JSAPI",
      "openId": req.body.openid
      // "timeExpire": +formatTime(now + 5 * 60 * 1000)
    }
    let result = yield fetch(
      config.app.app + "/api/wechatpay/webPay", {
        method: 'POST',
        body: o
      })
    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    let payRes = yield fetch(
      config.app.cdcUrl + '/order/generatePay', {
        method: 'PUT',
        body: {
          orderNo: req.body.id,
          channel: "wechat-pay",
          channelId: "wechat-pay"
        },
        headers: {
          token: "5429ca08df50392c974c5e71b8db12ab"
        }
      });
    if (payRes.data.code != 200) {
      payRes.data.custom = true;
      throw payRes.data;
    }
    //加入task
    let payingTask = new PayingTask(req.body.id, req.body);
    payingTask.onChecked = function(args) {
      return co(function*() {
        if (args) {
          let result = yield getOrderFromApp(payingTask.data);
          if (result.scanPayResData && result.scanPayResData.result_code ==
            "SUCCESS" &&
            result.scanPayResData.trade_state == "SUCCESS") {
            let payObj = {};
            let message = result.scanPayResData;
            payObj.payments = [{
              id: message.transaction_id,
              channel: "wechat-pay",
              channelId: "wechat-pay",
              amount: (+message.total_fee) / 100,
              received: (+message.total_fee) / 100,
              payMode: "pay",
              createTime: new Date().getTime(),
              extended: {
                trade_type: message.trade_type
              }
            }];
            payObj.statusType = "weixinorder"
            payObj.orderNo = message.out_trade_no;
            payObj.amountDue = (+message
              .total_fee) / 100;
            result = yield completeOrderToFbs(payObj);
          } else {
            result = yield cancelOrderToFbs(payingTask.orderId);
          }
          taskManage.removeTask(payingTask);
        } else {
          taskManage.removeTask(payingTask);
        }
      }).catch(function(e) {
        taskLogger.error({
          task: payingTask,
          error: e.stack || e.message || e.statusMessage || e
        })
      })
    }
    taskManage.add(payingTask);
    res.json(result.data);
  })

  router.get('/pay/notify/alipay', function(req, res, next) {
    console.log("xxx");
    next();
  })


}
